package com.zcl.security;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.zcl.dao.User;
import com.zcl.mapper.UserMapper;
import com.zcl.util.GetCurrentUserDetails;

/**
 * Created by fengch on 2017/5/29.
 */
public class MyUserDetailsService implements UserDetailsService {
	@Autowired
	UserMapper userMapper;
	Logger logger = Logger.getLogger(MyUserDetailsService.class);
	//注意点：数据库设计时，权限值应为ROLE_**
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	User user = null;
    	try {
    		user = userMapper.userQueryByName(username);
    		logger.info("获取角色信息");
    		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    		List<Map<String, String>> roleList = userMapper.roleQueryByName(username);
    		for (Map<String, String> role : roleList) {
				logger.info("用户权限为："+role);
				GrantedAuthority authority = new SimpleGrantedAuthority(role.get("authority"));
				authorities.add(authority);
			}
    		user.setAuthorities(authorities);
    	}catch (Exception e) {
			e.printStackTrace();
		}
    	if (user == null) {
			throw new UsernameNotFoundException("用户名或密码不正确");
		}
    	System.out.println("username : "+user.getUsername());
    	System.out.println("password : "+user.getPassword());
    	Map<String, String> map = new HashMap<String, String>();
    	Date date=new Date();   
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    	String lastlogintime = df.format(date);
    	map.put("lastlogintime", lastlogintime);
    	map.put("userName", username);
    	userMapper.lastLoginTime(map);
    	return user;
    }
}
